//
//  MCGoodsManageViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/20.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCGoodsManageViewController: MCViewController {
    
    public var goodsId : Int = 0
    
    
    private var goodsManageHeadmodel = MCGoodsManageHeadModel()
    
    var settingView : MCGoodsManageSettingView!
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    @objc func keyboardConfirmClicked() {
        self.view.endEditing(true)
        
        let para = [
            "commission" : headView.proportionView.textField.text ?? "",
            "goodsId"    : self.goodsId
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_setGoodsCommission, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            MCHUD_text(message: "设置佣金比例成功", view: self.view, delay: 1.2)
            
        }, dislike: { (response) in }) { (error) in }
    }

    
    @objc func rightButtonClicked() {
        let vc = MCShareGoodsViewController()
        vc.goodsId = goodsId
        vc.goodsName = goodsManageHeadmodel.goodsName
        vc.lowestPrice = goodsManageHeadmodel.lowestPrice.intValue
        vc.suggestedPrice =
            goodsManageHeadmodel.suggestedPrice.intValue
        vc.gooodsImage = goodsManageHeadmodel.goodsPicture
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    
    @objc func freightViewEvent() {
        
        let vc = MCFreightViewController()
        vc.delegate = self
        vc.currentFreightTemplateId = goodsManageHeadmodel.freightTemplateId.intValue
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func editButtonEvent() {
        
        if goodsManageHeadmodel.type == 0 {
            MCHUD_text(message: "平台商品不可编辑", view: self.view, delay: 1.2)
            return
        }
        
        let vc = MCNewGoodsViewController()
        vc.isEditGoods = true
        vc.goodsId = goodsId
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }

    
    
    @objc func selectedButtonClicked() {
    
        sectionHeadView.selectedButton.isSelected = !sectionHeadView.selectedButton.isSelected
        
        for model in self.dataArrayM {
            let subModel = model as! MCGoodsManageModel
            subModel.isSelected = sectionHeadView.selectedButton.isSelected
        }

        self.tableView.reloadData()
    }
    
    @objc func editSpecificationsButtonClicked() {
        
        if goodsManageHeadmodel.type == 0 {
            MCHUD_text(message: "平台商品不可编辑", view: self.view, delay: 1.2)
            return
        }
        let vc = MCSpecificationsViewController()
        vc.goodsId = goodsId
        vc.type = 1
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func settingButtonClicked() {
        
        var isSelected = false
        
        for model in dataArrayM {
            let tempModel = model as! MCGoodsManageModel
            if tempModel.isSelected {
                isSelected = true
            }
        }
        
        if !isSelected {
            MCHUD_text(message: "请选择要修改的货品", view: self.view, delay: 1.2)
            return
        }
        
        
        let arrayM = NSMutableArray()
        
        var settlementPrice_min = INT_MAX
        var taxSettlementPrice_min = INT_MAX
        var inventoryNum_min = INT_MAX
        var salePrice_min = INT_MAX
        var profitRate_min = INT_MAX

        
        
        for model in self.dataArrayM {
            let subModel = model as! MCGoodsManageModel
            if subModel.isSelected {
                arrayM.add(subModel.productId)
            }

            if settlementPrice_min > subModel.settlementPrice {
                settlementPrice_min = Int32(subModel.settlementPrice)
            }
         
            if taxSettlementPrice_min > subModel.taxSettlementPrice {
                taxSettlementPrice_min = Int32(subModel.taxSettlementPrice)
            }
            
            
            if salePrice_min > subModel.salePrice {
                salePrice_min = Int32(subModel.salePrice)
            }

            if inventoryNum_min > subModel.inventoryNum {
                inventoryNum_min = Int32(subModel.inventoryNum)
            }
            
            if profitRate_min > subModel.profitRate.intValue {
                profitRate_min = Int32(subModel.profitRate.intValue)
            }
        }
        
        
        let model = self.dataArrayM[0] as! MCGoodsManageModel
        model.inventoryNum = Int(inventoryNum_min)
        model.salePrice = Int(salePrice_min)
        model.settlementPrice = Int(settlementPrice_min)
        model.taxSettlementPrice = Int(taxSettlementPrice_min)
        model.profitRate = NSNumber.init(value: profitRate_min)

        
        let vc = MCCustomSpecificationsViewController()
        vc.goodsModel = goodsManageHeadmodel
        vc.specModel = model
        vc.productIdList = arrayM
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "goodsId" : goodsId,
            "storeId" : MCUserinfo_getStoreId()
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_merchantStoreGoodsManage, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as! [String : AnyObject]
            
            self.goodsManageHeadmodel = MCGoodsManageHeadModel()
            self.goodsManageHeadmodel.setValuesForKeys(dataDict)
            self.headView.model = self.goodsManageHeadmodel
            
            self.sectionHeadView.selectedButton.isSelected = false
            
            self.dataArrayM.removeAllObjects()
            let productVoList = dataDict["productVoList"] as! NSArray
            for dict in productVoList {
                let model = MCGoodsManageModel()
                model.setValuesForKeys(dict as! [String : Any])
                self.dataArrayM.add(model)
            }
            self.tableView.reloadData()
            
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "商品管理"
        self.view.backgroundColor = UIColor.white
        tableView.tableHeaderView = headView
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_share_black"), target: self, selector: #selector(rightButtonClicked))
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 44, 0))
        }
        
        view.addSubview(settingButton)
        settingButton.snp.remakeConstraints { (make) ->Void in
            make.right.bottom.equalTo(view)
            make.size.equalTo(CGSize.init(width: MCScreenWidth / 2, height: 44))
        }
        
        view.addSubview(editSpecificationsButton)
        editSpecificationsButton.snp.remakeConstraints { (make) ->Void in
            make.left.bottom.equalTo(view)
            make.size.equalTo(CGSize.init(width: MCScreenWidth / 2, height: 44))
        }

    }
    
    func MCAddToolBar(textField:UITextField) {
        let bar = UIToolbar.init(frame: CGRect.init(x: 0, y: 0, width: MCScreenWidth, height: 44))
        let button = UIButton.init(frame: CGRect.init(x: MCScreenWidth-80, y: 7, width: 70, height: 30))
        button.layer.cornerRadius = 5
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor.MCMain.cgColor
        button.layer.borderWidth = 1
        button.setTitle("确认", for: UIControlState.normal)
        button.setTitleColor(UIColor.MCMain, for: UIControlState.normal)
        button.titleLabel?.font = MCFont(14)
        button.addTarget(self, action: #selector(keyboardConfirmClicked), for: UIControlEvents.touchUpInside)
        bar.addSubview(button)
        bar.layoutIfNeeded()
        bar.sendSubview(toBack: bar.subviews.last!)
        textField.inputAccessoryView = bar
    }

    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var headView: MCGoodsManageHeadView = {
        let view = MCGoodsManageHeadView()
        
        
        view.proportionView.textField.keyboardType = UIKeyboardType.numberPad
        view.proportionView.textField.delegate = self
        MCAddToolBar(textField: view.proportionView.textField)
        
        view.freightView.contentButton.addTarget(self, action: #selector(freightViewEvent), for: UIControlEvents.touchUpInside)
        view.editButton.addTarget(self, action: #selector(editButtonEvent), for: UIControlEvents.touchUpInside)

        return view
    }()
    
    lazy var sectionHeadView: MCGoodsManageSectionView = {
        let view = MCGoodsManageSectionView()
        view.selectedButton.addTarget(self, action: #selector(selectedButtonClicked), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    lazy var settingButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.MCMain
        button.titleLabel?.font = MCFont(14)
        button.setTitle("批量设置", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(settingButtonClicked), for: UIControlEvents.touchUpInside)

        return button
    }()
    
    lazy var editSpecificationsButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.MCAssist
        button.titleLabel?.font = MCFont(14)
        button.setTitle("规格编辑", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(editSpecificationsButtonClicked), for: UIControlEvents.touchUpInside)
        
        return button
    }()
}

extension MCGoodsManageViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        sectionHeadView.type = goodsManageHeadmodel.type.intValue
        return sectionHeadView
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = self.dataArrayM[indexPath.row] as! MCGoodsManageModel
        let str = model.specStr
        let width : CGFloat = 70
        let sss = (MCScreenWidth - 40 - 40 - width * 3)
        
        let height = str.MCString_getHeight(font: MCFont(12), width: sss) + 20
        
        return height
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCGoodsManageCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.currentRow = indexPath.row
        cell.delegate = self
        cell.model = self.dataArrayM[indexPath.row] as! MCGoodsManageModel
        cell.type = goodsManageHeadmodel.type.intValue
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
}

extension MCGoodsManageViewController : MCGoodsManageCellDelegate {

    func MCGoodsManageCellEdit(row: Int) {
        let model = self.dataArrayM[row] as! MCGoodsManageModel
        let vc = MCCustomSpecificationsViewController()
        vc.goodsModel = goodsManageHeadmodel
        vc.specModel = model
        vc.productIdList = [model.productId]
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}

extension MCGoodsManageViewController : MCGoodsManageSettingViewDelegate {
    
    func MCGoodsManageSettingView_editStoreProductInfo(count: Int, sale: Double, settle: Double, productIdList: NSArray,status:Int) {
        
        let para = [
            "goodsId" : self.goodsId,
            "productIdList" : productIdList,
            "storeId"   :MCUserinfo_getStoreId(),
            "inventoryNum" : count,
            "isStockWarn" : 0,
            "salePrice"   : sale*100,
            "settlementPrice" : settle*100,
            "storeUserId"   : MCUserinfo_getUserId(),
            "status"  : status
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_editStoreProductInfo, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in

            MCHUD_text(message: "设置成功", view: self.view, delay: 1.5)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                self.sectionHeadView.selectedButton.isSelected = false
                self.settingView.removeFromSuperview()
                self.sendNetworking()
            })

        }, dislike: { (response) in }) { (error) in }
    }
}


extension MCGoodsManageViewController : MCFreightViewControllerDelegate {
   
    func MCFreightViewControllerSelectedFreightTemplate(model: MCFreightModel) {

        let para = [
            "freightTemplateId" : model.freightTemplateId,
            "goodsId"    : self.goodsId
            ] as [String : Any]

        MCNetwork_post(url: JAVA_updateFreightTemplate, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            MCHUD_text(message: "更改运费模板成功", view: self.view, delay: 1.2)
            self.goodsManageHeadmodel.freightTemplateName = model.name
            self.goodsManageHeadmodel.freightTemplateId =  model.freightTemplateId
            self.headView.freightView.contentButton.isSelected = true
            self.headView.freightView.contentButton.setTitle(model.name, for: UIControlState.normal)
        }, dislike: { (response) in }) { (error) in }
    }
}

extension MCGoodsManageViewController : UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
       
        if MCUserinfo_getLevel() != MCRole_manager {
            MCHUD_text(message: "只有店主才可编辑", view: self.view, delay: 1.2)
            return false
        }

        return true
    }
}

